package com.jianggujin.redis.node;

import com.jianggujin.redis.config.ConnectionConfig;

import lombok.Getter;
import redis.clients.jedis.Jedis;

@Getter
public class RedisConnection {
    private volatile Jedis client;
    private final ConnectionConfig config;

    public RedisConnection(ConnectionConfig config) {
        this.config = config;
    }

    private static Jedis newClient(ConnectionConfig config) {
        return new Jedis(config.getHost(), config.getPort(), config.getConnectionTimeout(), config.getSoTimeout());
    }

    public boolean isValited() {
        return client != null && client.isConnected() && !client.getClient().isBroken();
    }

    public Jedis getClient() {
        if (!isValited()) {
            synchronized (this) {
                if (!isValited()) {
                    // 重试三次
                    for (int i = 0; i < 3; i++) {
                        try {
                            connect();
                            if (isValited()) {
                                break;
                            }
                            Thread.sleep(500);
                        } catch (Exception e) {
                        }
                    }
                }
            }
        }
        return client;
    }

    public void connect() {
        if (client != null) {
            if (client.getClient().isBroken()) {
                client.close();
                client = null;
            } else if (client.isConnected()) {
                return;
            }
        }
        if (client == null) {
            client = newClient(config);
        }
        client.connect();
        if (config.getAuth() != null && config.getAuth().length() > 0) {
            client.auth(config.getAuth());
        }
    }

    public void disconnect() {
        if (client != null) {
            if (client.isConnected()) {
                client.close();
            }
            client = null;
        }
    }

    @Override
    public String toString() {
        return config.getName();
    }
}
